# Copyright [2011] [Ilya Rudakov]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ConfigParser import RawConfigParser, ConfigParser, SafeConfigParser

import os
import shutil
import uuid
import zipfile
from django.core.exceptions import ObjectDoesNotExist
from job_manager.models import FeedGroup, Feed
from job_manager.services.audit_service import audit
from job_manager.services.java_job_helper import handle_java_job
from job_manager.services.python_job_helper import handle_python_job
from job_manager.utils.logging_utils import getlogger


__author__ = 'irudakov'

LOG = getlogger(__name__)

JAVA_TYPE = "JAVA"
PYTHON_TYPE = "PYTHON"

def add_feed_group(**properties):
    name = properties['name']
    return FeedGroup.objects.create(name=name)

def delete_job_group_(job_group_id):
    initial_job_group = FeedGroup.objects.get(mutable=False)
    try:
        job_group = FeedGroup.objects.get(id=job_group_id)
        jobs = job_group.get_feeds()
        for job in jobs:
            job.feed_group = initial_job_group
            job.save()
        job_group.delete()
    except ObjectDoesNotExist, ignore:
        LOG.debug("Somebody tried to delete job group but it wasn't found")

def add_feed(**properties):
    name = properties['name']
    feed_group = properties['feed_group']
    description = properties['description']
    feed_file = properties['file']
    user = properties['user']

    LOG.debug("Creating feed with name: %s" % name)

    feed_name = name.lower().replace(" ", "_")
    new_feed_path = os.path.abspath("./jobs_storage/%s_%s" % (feed_name, uuid.uuid1()))
    try:
        os.mkdir(new_feed_path)
        handle_feed_file(feed_file, new_feed_path + "/") 

        feed_type = get_feed_type(new_feed_path)

        LOG.debug("Feed type %s" % feed_type)

        if feed_type == JAVA_TYPE:
            handle_java_job(new_feed_path, feed_name)
        elif feed_type == PYTHON_TYPE:
            handle_python_job(new_feed_path)
        else:
            LOG.info("Unknown job type! Removing %s..." % new_feed_path)
            shutil.rmtree(new_feed_path)
            return None
        
        feed = Feed.objects.create(name=name, description=description, path=new_feed_path, feed_group=feed_group, type=feed_type)
        audit(job=feed, user=user, action="C")
        return feed
    except OSError:
        LOG.debug("Feed with name %s already exist!" % name)
        return None

def get_feed_type(path):
    LOG.debug("Getting feed type...")
    type_dirs = filter(lambda dir: dir == ".java" or dir == ".python", os.listdir(path))
    LOG.debug("feed type: %s" % type_dirs)

    if not len(type_dirs): return None

    return {
        ".java" : JAVA_TYPE,
        ".python": PYTHON_TYPE
    }[type_dirs[0]]

def del_feed(feed_id):
    try:
        feed = Feed.objects.get(id=feed_id)
        path = feed.path

        LOG.debug("Deleting feed(ID:%s)" % feed_id)

        try:
            shutil.rmtree(path)
            feed.delete()
        except OSError:
            LOG.debug("Feed deletion failed(ID:%s)" % feed_id)
            return False
        return True
    except ObjectDoesNotExist:
        LOG.debug("Somebody tried to delete job but it wasn't found")
        return True

def set_group(feed_id, receiver_group_id, user):
    try:
        LOG.debug("Setting new group for feed id:%s" % feed_id)

        feed = Feed.objects.get(id=feed_id)
        receiver_group = FeedGroup.objects.get(id=receiver_group_id)
        feed.feed_group = receiver_group
        feed.save()
        audit(job=feed, user=user, action="GC")
    except ObjectDoesNotExist, ignore:
        LOG.debug("Somebody tried to change job group but job wasn't found")

def update_job_name_(job_id, name):
    try:
        job = Feed.objects.get(id=job_id)
        job.name = name
        job.save()
    except ObjectDoesNotExist, ignore:
        LOG.debug("Somebody tried to update job name but job wasn't found")

def update_job_description_(job_id, description):
    try:
        job = Feed.objects.get(id=job_id)
        job.description = description
        job.save()
    except ObjectDoesNotExist, ignore:
        LOG.debug("Somebody tried to update job description but job wasn't found")

def update_job_group_name_(job_group_id, name):
    try:
        job_group = FeedGroup.objects.get(id=job_group_id)
        job_group.name = name
        job_group.save()
    except ObjectDoesNotExist, ignore:
        LOG.debug("Somebody tried to update job group name but job group wasn't found")

def handle_feed_file(feed_file, destination_path):
    zip_file = zipfile.ZipFile(feed_file.file)
    zip_file.extractall(destination_path)
    zip_file.close()